<script setup lang="ts">
import {
  User,
  EditPen,
    Coordinate,
  SwitchButton,
  CaretBottom, Iphone, Postcard
} from '@element-plus/icons-vue'
import useUserInfoStore from '@/stores/userInfo'
import {ElMessage, ElMessageBox} from "element-plus"
import {useRouter} from "vue-router"
import {useTokenStore} from '@/stores/token'
import charts1 from './charts/AdminCharts.vue'
import charts2 from './charts/NormalCharts.vue'
import charts3 from './charts/SysCharts.vue'
import {ref,onMounted} from "vue"
import {useInfoStore} from "@/stores/infos.js"
import {sendECode} from "@/api/email.js"
import {useBlackSotre} from '@/stores/black'
import emitter from "@/utils/buts.js"
import {userExist, userRegisterAService, userUpdateName, userUpdatePass} from "@/api/user.js"
import {getMessages, sendInnerMessage} from "@/api/message.js";
const tokenStore = useTokenStore()
const messages = useInfoStore()
const userInfoStore = useUserInfoStore()
const isSmsCodeSending = ref(true)
const isSmsCodeSending2 = ref(true)
const router = useRouter()
if (userInfoStore.info.name===null){
  ElMessage.warning('请登录')
  router.push('/login')
}
let avas = ""
if (userInfoStore.info.userType === 'ENTERPRISE_ADMIN') {
  avas = ref("https://img.ixintu.com/upload/jpg/20210523/8c0a1453a313f351f2d913a18f6ab452_10519_180_205.jpg!ys")
}else if (userInfoStore.info.userStatus === 'CANDIDATE') {
  avas = "https://bpic.588ku.com/element_origin_min_pic/19/04/09/e3330d623cad123abc8545573a86cc38.jpg"
}else {
  avas = "https://img.88icon.com/download/jpg/20201226/9d64c2d320c079cbd4f38f10e066dc71_512_512.jpg!bg"
}
const menu =ref()
const smsCodeBtnText = ref('获取验证码')
const smsCodeBtnText2 = ref('获取验证码')
if(router.currentRoute.value.path==='/layout'){
  menu.value = "首页"
}
if(router.currentRoute.value.path==='/layout/clientM' && userInfoStore.info.userType==="SYSTEM_ADMIN"){
  menu.value = "首页"
}
const sendMessage = async (email,type) => {
  if (email===null){
    ElMessage.error('请输入邮箱')
    return
  }
  if (type===1){
    startECodeCountdown()
  }else {
    startECodeCountdown2()
  }
  let res = await sendECode(email)
  // ElMessage.success(res)
}
const startECodeCountdown = () => {
  let count = 60
  const timer = setInterval(() => {
    if (count <= 0) {
      clearInterval(timer)
      smsCodeBtnText.value = '获取验证码'
      isSmsCodeSending.value = true
    } else {
      smsCodeBtnText.value = `${count}秒后重试`
      isSmsCodeSending.value = false
      console.log(isSmsCodeSending.value)
      count--
    }
  }, 1000)
}
const startECodeCountdown2 = () => {
  let count = 60
  const timer = setInterval(() => {
    if (count <= 0) {
      clearInterval(timer)
      smsCodeBtnText2.value = '获取验证码'
      isSmsCodeSending2.value = true
    } else {
      smsCodeBtnText2.value = `${count}秒后重试`
      count--
      isSmsCodeSending2.value =  false
    }
  }, 1000)
}
const rePassword = ref(false);
const infos = ref(false);
const rePhoneNumber = ref(false);
const reEmail = ref(false);
const sendMessages = ref(false);
const contents = ref('');
//条目被点击后
const handleCommand = (command)=>{
  if (command === 'logout'){
    //退出登录
    ElMessageBox.confirm(
        '请问您确定要退出吗',
        '提醒',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          //清空pinia中存储的token及个人信息
          await userExist(userInfoStore.info.id)
          tokenStore.removeToken()
          userInfoStore.removeInfo()
          messages.clearInfo()
          //跳转到登录页面
          if(userInfoStore.info.userType==="SYSTEM_ADMIN"){
            await router.push('/syslogin')
          }else {
            await router.push('/login')
          }
          ElMessage({
            type: 'success',
            message: '退出登录',
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消',
          })
        })
  }else if (command === 'info'){
    //修改用户名
    infos.value = ref(true)
  }else if (command === 'rePhoneNumber'){
    //修改手机号
    rePhoneNumber.value = ref(true)
  }else if (command === 'reEmail'){
    //修改邮箱
    reEmail.value = ref(true)
  }else if (command === 'sendMessage'){
    //发送消息
    sendMessages.value = ref(true)
  }else {
    //修改密码
    rePassword.value = ref(true)
  }

}

const menuType = [{name:'发起审批',value:'/layout/initiateA', unicode: '\ue620' }, {name:'我的审批',value:'/layout/underwayA',unicode: '\ue6d4' },
{name:'历史审批',value:'/layout/historyA', unicode: '\ue661'}, {name:'审批管理',value:"/layout/approvalM",unicode: '\ue668'}, {name:'用户管理',value:"/layout/enterM",unicode: '\ue641'}, {name:'企业管理',value:"/layout/UserM",    unicode: '\ue678'}]
let menus=[]
switch (userInfoStore.info.userType) {
  case 'NORMAL_USER':
    for (let i=0;i<3;i++) {
      menus[i] = menuType[i]
    }
    break;
    case 'ENTERPRISE_ADMIN':
      for (let i=3;i<6;i++) {
        menus[i-3] = menuType[i]
      }
      break;
    default:
      menus[0] = {name:'客户管理',value:"/layout/clientM",unicode: '\ue678'}
        break;
}

const newName = ref(null);
const updateName = async () => {
  let res
  try {
    res = await userUpdateName(userInfoStore.info.id,newName.value)
    ElMessage.success(res ||'修改成功')
    infos.value=false
    userInfoStore.info.name=newName.value
    newName.value=null
    userInfoStore.info.username = newName.value
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '修改失败')
  }
}
const newPass = ref(null);
const oldPass = ref(null);
const renNewPass = ref(null);
const updatePass = async () => {
  let res
  if (oldPass.value===null || newPass.value===undefined || renNewPass.value===null) {
    ElMessage.error("请输入全部密码")
    return;
  }
  if (newPass.value !== renNewPass.value) {
    ElMessage.error("两次密码不一致")
    return;
  }
  try {
    res = await userUpdatePass(userInfoStore.info.id,oldPass.value,newPass.value)
    ElMessage.success(res ||'修改成功')
    newPass.value=null
    oldPass.value=null
    rePassword.value=false
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '修改失败')
  }
}
const dates = ref<[Date, Date]>([
  // new Date(2000, 10, 10, 10, 10),
  // new Date(2000, 10, 11, 10, 10),
])
const sendInfo=async () => {
  if (contents.value==='' || dates.value==='') {
    return;
  }
  let res = await sendInnerMessage(userInfoStore.info.id,contents.value,dates.value[0].toISOString(),dates.value[1].toISOString())
  sendMessages.value = false
  ElMessage.success("消息"+res)
}
const newEmail = ref(null);
const oldCode = ref(null);
const eCode = ref(null);
const updateEmail = async () => {
  let res
  if ( oldCode.value===ref(null) ) {
    ElMessage.error("请输入旧邮箱验证码")
    return;
  }
  if (newEmail.value === userInfoStore.info.email) {
    ElMessage.error("两次邮箱相同")
    return;
  }
  try {
    res = await userUpdateEmail(userInfoStore.info.id,oldCode.value,newEmail.value,eCode.value)
    ElMessage.success(res ||'修改成功')
    newEmail.value=ref(null)
    eCode.value=ref(null)
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '修改失败')
  }
}

const isBlack = useBlackSotre()
const toggleDark = () =>{
  let element = document.getElementById('aside');
  let element1 = document.getElementById('middle');
  let element2 = document.getElementById('head');
  let element3 = document.getElementById('menu');
  if (isBlack.black===false){
    element.style.background = 'white';
    element1.style.background = 'linear-gradient(220.55deg, #EAEAEA 0%, #8B8B8B 100%)';
    element2.style.background = 'white';
    element3.style.background = 'white';
  }else {
    element.style.background = 'grey';
    element1.style.background = 'linear-gradient(220.55deg, #565656 0%, #181818 100%)';
    element2.style.background = 'grey';
    element3.style.background = 'grey';
  }
}
emitter.on("login", () => {
  toggleDark()
});
const getMessage = async ()=>{
  await getMessages(userInfoStore.info.id)
}
getMessage()

onMounted(()=>{
  toggleDark()
})

const userInfos = [userInfoStore.info]
</script>

<template >
  <el-container class="layout-container">
    <!-- 头部区域 -->
    <el-header id="head">
      <div v-if="userInfoStore.info.userType!=='SYSTEM_ADMIN'">用户名：<strong>{{userInfoStore.info.username}}</strong>&nbsp&nbsp&nbsp
        企业：<strong>{{userInfoStore.info.enterpriseName}}</strong>
        <el-button style="margin-left: 10px;" @click="router.push('/layout');menu = '首页'">首页</el-button></div>
      <div v-if="userInfoStore.info.userType==='SYSTEM_ADMIN'">用户名：<strong>{{userInfoStore.info.username}}</strong>&nbsp&nbsp&nbsp
        <el-button style="margin-left: 10px;" @click="router.push('/layout');menu = '首页'">首页</el-button></div>
      <p style="font-size: 40px;font-family: 宋体,serif;margin-right: 30vh">{{menu}}</p>
      <!--       下拉菜单-->
      <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                              <el-avatar
                                  :src="avas"
                              />
                        <el-icon>
                            <CaretBottom />
                        </el-icon>
                    </span>
        <template #dropdown>
          <el-dropdown-menu>
            <!--              command 条目被点击后触发，在事件上可以声明一个参数，接收对应的指令-->
            <el-dropdown-item command="info" :icon="User" >更换用户名</el-dropdown-item>
            <el-dropdown-item command="rePhoneNumber" :icon="Iphone">更换手机号</el-dropdown-item>
            <el-dropdown-item command="reEmail" :icon="Postcard">更换邮箱</el-dropdown-item>
            <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
            <el-dropdown-item command="sendMessage" :icon="Coordinate" v-if="userInfoStore.info.userType!=='NORMAL_USER'">发送消息</el-dropdown-item>
            <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </el-header>
    <el-dialog
        v-model="infos"
        title="修改用户名"
        width="1000"
        :before-close="null"
    >请输入新用户名：<el-input style="width: 60%" v-model="newName"></el-input>
      <el-button type="primary" style="margin-left: 2vh" @click="updateName()">提交</el-button>
      <el-button type="info" @click="infos=false">取消</el-button>
    </el-dialog>

    <el-dialog
        v-model="rePassword"
        title="修改密码"
        width="1000"
        :before-close="null"
    >
      <div style="text-align: center;margin-top: 2vh">
      请输入旧密码：<el-input :show-password="true" v-model="oldPass" style="width: 60%;margin-bottom: 2vh;margin-left: 3vh"></el-input><br>
      请输入新密码：<el-input :show-password="true" v-model="newPass" style="width: 60%;margin-bottom: 2vh;margin-left: 3vh"></el-input><br>
      请再次输入新密码：<el-input  :show-password="true" v-model="renNewPass" style="width: 60%;"></el-input><br>

      <el-button type="primary"  @click="updatePass()" style="margin-top: 2vh">提交</el-button>
      <el-button type="info" @click="rePassword=false" style="margin-top: 2vh">取消</el-button></div>
    </el-dialog>
    <el-dialog
        v-model="rePhoneNumber"
        title="修改手机号"
        width="1000"
        :before-close="null"
    >
      <div style="font-size: 30px;text-align: center;margin-bottom: 2vh">当前手机号：{{userInfoStore.info.phone}}</div>
      请输入旧手机号验证码：<el-input style="width: 60%;margin-left: 3vh"></el-input> <el-button >发送</el-button><br><br>
      请输入新手机号：<el-input style="width: 60%;margin-left: 7.6vh"></el-input><br><br>
      请输入新手机号验证码：<el-input style="width: 60%;margin-left: 3vh"></el-input> <el-button>发送</el-button><br><br>
      <div style="text-align: center;margin-top: 2vh">
        <el-button type="primary"  @click="updatePass()">提交</el-button>
        <el-button type="info" @click="rePhoneNumber=false">取消</el-button></div>
    </el-dialog>
    <el-dialog
        v-model="reEmail"
        title="修改邮箱"
        width="1000"
        :before-close="null"
    >
      <div style="font-size: 30px;text-align: center;margin-bottom: 2vh">当前邮箱：{{userInfoStore.info.email}}</div>
      请输入旧邮箱验证码：<el-input style="width: 60%;margin-left: 3vh" v-model="oldCode"></el-input> <el-button @click="sendMessage(userInfoStore.info.email,1)" :disabled="!isSmsCodeSending">{{smsCodeBtnText}}</el-button><br><br>
      请输入新邮箱：<el-input style="width: 60%;margin-left: 7.5vh" v-model="newEmail"></el-input><br><br>
      请输入新邮箱验证码：<el-input style="width: 60%;margin-left: 3vh" v-model="eCode"></el-input> <el-button @click="sendMessage(newEmail,2)" :disabled="!isSmsCodeSending2">{{smsCodeBtnText2}}</el-button><br><br>
      <div style="text-align: center;margin-top: 2vh">
        <el-button type="primary"  @click="updateEmail()">提交</el-button>
        <el-button type="info" @click="reEmail=false">取消</el-button></div>
    </el-dialog>
    <el-dialog
        v-model="sendMessages"
        title="发送站内公告"
        width="1000"
        :before-close="null"
    >
      <div v-if="userInfoStore.info.userType==='SYSTEM_ADMIN'">发送目标：所有用户</div>
      <div v-if="userInfoStore.info.userType==='ENTERPRISE_ADMIN'" style="margin-bottom: 2vh;font-size: 20px">发送目标：{{userInfoStore.info.enterpriseName}}全体用户</div>
      <el-input type="textarea" style="width: 85%;margin-left: 10vh" v-model="contents">请输入内容</el-input>
      <div class="block" style="margin-top: 1vh;margin-left: 20vh">
        <span class="demonstration">请选择生效日期范围：</span>
        <el-date-picker
            v-model="dates"
            type="datetimerange"
            range-separator="To"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
      </div>
      <div style="text-align: center;margin-top: 2vh">
        <el-button type="primary"  @click="sendInfo()">发送</el-button>
        <el-button type="info" @click="sendMessages=false">取消</el-button></div>
    </el-dialog>
    <!-- 左侧菜单 -->
    <el-aside width="200px" id="aside">
      <!--菜单标签-->
      <el-menu active-text-color="#6991c7" text-color="black"
               router id="menu">
        <el-menu-item v-for="(user,i) in menus" :index="user.value" class="sp" @click="menu = user.name">
          <svg t="1741083460670" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1182" width="200" height="200"><path d="M285.642105 44.786526l180.924632 104.448a43.115789 43.115789 0 0 1 21.557895 37.338274v208.917558a43.115789 43.115789 0 0 1-21.557895 37.338274L285.642105 537.276632a43.115789 43.115789 0 0 1-43.115789 0l-180.924632-104.448a43.115789 43.115789 0 0 1-21.557895-37.338274V186.5728a43.115789 43.115789 0 0 1 21.557895-37.338274L242.526316 44.786526a43.115789 43.115789 0 0 1 43.115789 0z m-21.557894 49.777179L93.938526 192.792253v196.467873L264.084211 487.488674l170.134905-98.228548V192.792253L264.084211 94.563705zM781.473684 44.786526l180.924632 104.448a43.115789 43.115789 0 0 1 21.557895 37.338274v208.917558a43.115789 43.115789 0 0 1-21.557895 37.338274L781.473684 537.276632a43.115789 43.115789 0 0 1-43.115789 0l-180.924632-104.448a43.115789 43.115789 0 0 1-21.557895-37.338274V186.5728a43.115789 43.115789 0 0 1 21.557895-37.338274L738.357895 44.786526a43.115789 43.115789 0 0 1 43.115789 0z m-21.557895 49.777179l-170.145684 98.228548v196.467873L759.915789 487.488674l170.134906-98.228548V192.792253L759.915789 94.563705zM533.557895 486.723368l180.924631 104.448a43.115789 43.115789 0 0 1 21.557895 37.338274v208.917558a43.115789 43.115789 0 0 1-21.557895 37.338274L533.557895 979.213474a43.115789 43.115789 0 0 1-43.11579 0l-180.924631-104.448a43.115789 43.115789 0 0 1-21.557895-37.338274V628.509642a43.115789 43.115789 0 0 1 21.557895-37.338274L490.442105 486.723368a43.115789 43.115789 0 0 1 43.11579 0z m-21.557895 49.777179l-170.145684 98.228548v196.467873L512 929.425516l170.134905-98.228548V634.729095L512 536.500547z" fill="#2976FF" p-id="1183"></path><path d="M533.557895 184.912842l180.924631 104.448a43.115789 43.115789 0 0 1 21.557895 37.338274v208.917558a43.115789 43.115789 0 0 1-21.557895 37.338273L533.557895 677.402947a43.115789 43.115789 0 0 1-43.11579 0l-180.924631-104.448a43.115789 43.115789 0 0 1-21.557895-37.338273V326.699116a43.115789 43.115789 0 0 1 21.557895-37.338274L490.442105 184.912842a43.115789 43.115789 0 0 1 43.11579 0z" fill="#FFFFFF" p-id="1184"></path><path d="M533.557895 184.912842l180.924631 104.448a43.115789 43.115789 0 0 1 21.557895 37.338274v208.917558a43.115789 43.115789 0 0 1-21.557895 37.338273L533.557895 677.402947a43.115789 43.115789 0 0 1-43.11579 0l-180.924631-104.448a43.115789 43.115789 0 0 1-21.557895-37.338273V326.699116a43.115789 43.115789 0 0 1 21.557895-37.338274L490.442105 184.912842a43.115789 43.115789 0 0 1 43.11579 0z m-21.557895 49.777179l-170.145684 98.228547v196.467874L512 627.614989l170.134905-98.228547V332.918568L512 234.690021z" fill="#44D7B6" p-id="1185"></path></svg>          <span >{{user.name}}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧主区域 -->
    <el-container >
      <div class="menu" v-if="router.currentRoute.value.path==='/layout'">
      <el-table style="width:150vh;margin-left:30vh;margin-top: -60vh ;border-radius: 10px" :data="userInfos" >
        <el-table-column prop="id" label="用户id" width="120" />
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="realName" label="真实名" width="100" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="enterpriseName" label="所属企业" width="180" v-if="userInfoStore.info.userType!=='SYSTEM_ADMIN'"/>
        <el-table-column prop="job" label="职务" width="100" />
        <el-table-column v-if="userInfoStore.info.userStatus==='CANDIDATE'" prop="userStatus"  label="账号状态" width="100" />
        <el-table-column v-if="userInfoStore.info.userStatus==='FREEZE'" prop="userStatus"  label="账号状态" width="100" />
      </el-table>
      <charts1 v-if="userInfoStore.info.userType==='ENTERPRISE_ADMIN'"></charts1>
      <charts2 v-if="userInfoStore.info.userType==='NORMAL_USER'"></charts2>
      <charts3 v-if="userInfoStore.info.userType==='SYSTEM_ADMIN'"></charts3>
      </div>
      <!-- 中间区域 -->

        <div id="middle" class="user-manage" ><router-view ></router-view></div>

      <!-- 底部区域 -->
      <el-footer>debug ©2025 Created by 在线审批系统</el-footer>
    </el-container>
  </el-container>
</template>

<style scoped lang="scss">
.layout-container {
  z-index: 100;
  height:84vh;
  .el-aside {
    //background: linear-gradient(to top, #ace0f9 0%,   #fff1eb 100%);
    .el-menu {
      border-right: none;
      margin-top: 60px;
      //background: #f5f5f5;
      height: 60vh;
      border-radius: 10px;
      margin-left: 10px;
    }
  }
  .sp{
    margin-top: 20px;
    width: 90%;
    height: 16vh;
    //margin-left: 5px;
    border-radius: 10px;
    background:linear-gradient(220.55deg, #5D85A6 0%, #0E2C5E 100%);
    font-size: 24px;
    font-family: 华文行楷,serif;
    color: bisque;
    cursor: pointer;
    transition: all 0.5s;
  }
  .sp:hover{
    transform: scale(1.1);
    box-shadow: 5px 5px 0px 0px  #07bccc;
    color: #07bccc;
  }
  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }

      &:active,
      &:focus {
        outline: none;
      }
    }
  }
  .user-manage{
    margin-left: 30vh;
    width: 153vh;
    height: 50vh;
    //background:linear-gradient(220.55deg, #EAEAEA 0%, #8B8B8B 100%);
    border-radius: 10px;
    margin-top: -58vh;
  }
  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    margin-top: 5vh;
    color: #666;
  }
}


</style>